package com.ruoyi.system.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.Socket;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.AppNsfwPic;
import com.ruoyi.system.service.IAppNsfwPicService;

/**
 * 图片鉴黄 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-07-11
 */
@Controller
@RequestMapping("/system/appNsfwPic")
public class AppNsfwPicController extends BaseController
{
    private String prefix = "system/appNsfwPic";
	
	@Autowired
	private IAppNsfwPicService appNsfwPicService;
	
	@RequiresPermissions("system:appNsfwPic:view")
	@GetMapping()
	public String appNsfwPic()
	{
	    return prefix + "/appNsfwPic";
	}
	
	/**
	 * 查询图片鉴黄列表
	 */
	@RequiresPermissions("system:appNsfwPic:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(AppNsfwPic appNsfwPic)
	{
		startPage();
        List<AppNsfwPic> list = appNsfwPicService.selectAppNsfwPicList(appNsfwPic);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出图片鉴黄列表
	 */
	@RequiresPermissions("system:appNsfwPic:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AppNsfwPic appNsfwPic)
    {
    	List<AppNsfwPic> list = appNsfwPicService.selectAppNsfwPicList(appNsfwPic);
        ExcelUtil<AppNsfwPic> util = new ExcelUtil<AppNsfwPic>(AppNsfwPic.class);
        return util.exportExcel(list, "appNsfwPic");
    }
	
	/**
	 * 新增图片鉴黄
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存图片鉴黄
	 */
	@RequiresPermissions("system:appNsfwPic:add")
	@Log(title = "图片鉴黄", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(MultipartFile upload, String fileName) {
		AppNsfwPic appNsfwPic = new AppNsfwPic();
		try {
			String avatar = FileUploadUtils.upload(Global.getUploadPath(), upload);
			String os = System.getProperty("os.name");  
			String cmd = "";
			if(os.toLowerCase().startsWith("win")){  
				cmd = Global.getUploadPath().substring(0,1) + ":" + avatar;
			}else {
				cmd = avatar;
			}
			System.out.println(avatar);
			System.out.println(cmd);
			System.out.println(Global.getUploadPath());
			//远程调用socket接口
			Socket socket = null;
			try {
				socket = getConnection("127.0.0.1", 8119);
				String resultStr = send(socket, cmd);
				String str = resultStr.trim().replaceAll("'", "\"");
				JSONObject obj = JSON.unmarshal(str, JSONObject.class);
				JSONObject data = obj.getObj(cmd);
				String sexy = new BigDecimal(data.getStr("sexy")).toPlainString();
				String drawings = new BigDecimal(data.getStr("drawings")).toPlainString();
				String hentai = new BigDecimal(data.getStr("hentai")).toPlainString();
				String porn = new BigDecimal(data.getStr("porn")).toPlainString();
				String neutral = new BigDecimal(data.getStr("neutral")).toPlainString();
	             
				String maxv = sexy;
				String maxn = "sexy";
				if(maxv.compareTo(drawings)<0) {
					maxv = drawings;
					maxn = "drawings";
				}
				if(maxv.compareTo(hentai)<0) {
					maxv = hentai;
					maxn = "porn cartoon";
				}
				if(maxv.compareTo(porn)<0) {
					maxv = porn;
					maxn = "porn";
				}
				if(maxv.compareTo(neutral)<0) {
					maxv = neutral;
					maxn = "neutral";
				}
				// {'D:/profile/upload/2019/07/11/568c40c2c5f9720242daf04bde7bf48a.png':
				// {'sexy': 0.022963677, 'drawings': 0.025316697, 'hentai': 0.1454492, 'porn':
				// 0.23056108, 'neutral': 0.57570934}}
				appNsfwPic.setPicLocation(avatar);
				appNsfwPic.setSexy(sexy);
				appNsfwPic.setDrawings(drawings);
				appNsfwPic.setHentai(hentai);
				appNsfwPic.setPorn(porn);
				appNsfwPic.setNeutral(neutral);
				appNsfwPic.setResult(  maxn );
				
				if (appNsfwPicService.insertAppNsfwPic(appNsfwPic) > 0) {
					return success();
				}

			} catch (Exception e) {
				System.out.println("image file path："+cmd);
				return AjaxResult.error("error, Failed to link remote service。");
			} finally {
				close(socket);
			}
			
			return error();

		} catch (IOException e) {
			e.printStackTrace();
			return error(e.getMessage());
		}

	}

	
    
	/**
	 * 修改图片鉴黄
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap)
	{
		AppNsfwPic appNsfwPic = appNsfwPicService.selectAppNsfwPicById(id);
		mmap.put("appNsfwPic", appNsfwPic);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存图片鉴黄
	 */
	@RequiresPermissions("system:appNsfwPic:edit")
	@Log(title = "图片鉴黄", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(AppNsfwPic appNsfwPic)
	{		
		return toAjax(appNsfwPicService.updateAppNsfwPic(appNsfwPic));
	}
	
	/**
	 * 删除图片鉴黄
	 */
	@RequiresPermissions("system:appNsfwPic:remove")
	@Log(title = "图片鉴黄", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(appNsfwPicService.deleteAppNsfwPicByIds(ids));
	}
	
	
	
	public Socket getConnection(String ip, int port) {
		Socket socket = null;
		try {
			socket = new Socket(ip, port);
			socket.setSoTimeout(30000);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return socket;
	}

	/*
	 * 发送报文
	 */
	public String send(Socket socket, String cmd) {
		InputStream in = null;
		OutputStream out = null;
		BufferedReader br = null;
		try {
			// in代表服务器到客户端的流
			in = socket.getInputStream();
			// 代表客户端到服务器的流
			out = socket.getOutputStream();

			// 输入执行命令
			PrintWriter printWriter = new PrintWriter(out, true);
			printWriter.write(cmd);
			printWriter.flush();

			// 接收执行命令结果
			br = new BufferedReader(new InputStreamReader(in));
			return br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	/*
	 * 关闭socket连接
	 */
	public void close(Socket socket) {
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		String jsons = "{'D:/profile/upload/2019/07/11/6fd735de32f8f35d80e247e53d89c735.png': {'sexy': 0.00013305669, 'hentai': 0.0016534707, 'porn': 0.0027034702, 'drawings': 0.0034435482, 'neutral': 0.9920664}}";
		String str = jsons.trim().replaceAll("'", "\"");
				
		JSONObject obj;
         try
         {
             obj = JSON.unmarshal(str, JSONObject.class);
             JSONObject data = obj.getObj("D:/profile/upload/2019/07/11/6fd735de32f8f35d80e247e53d89c735.png");
             
             String drawings = data.getStr("drawings");
             String hentai = data.getStr("hentai");
             String sexy = data.getStr("sexy");
             System.out.println(sexy);
             System.out.println(hentai);
             BigDecimal bd = new BigDecimal(sexy);
             System.out.println( bd.toPlainString());
             
         }
         catch (Exception e)
         {
        	 e.printStackTrace();
         }
         
        
         
       
	}
}
